<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\logic;

/**
 * 员工逻辑
 */
class Staff extends AdminBase
{
    /**
     * 获取员工列表
     */
    public function getStaffList($where = [], $field = 'a.*,b.name,c.branch_name,d.group_name', $order = 'c.sort desc,d.sort desc', $paginate = 0)
    {
        $this->modelStaff->alias('a');
        
        $join = [
                    [SYS_DB_PREFIX . 'company b', 'a.company_id = b.id'],
                    [SYS_DB_PREFIX . 'branch c', 'a.branch_id = c.id'],
                    [SYS_DB_PREFIX . 'group d', 'a.group_id = d.id'],
                ];
        $where['a.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        if(empty($where['a.w_status'])){
          $where['a.w_status']=2;
        }
        return $this->modelStaff->getList($where, $field, $order, $paginate,$join);
    }


    /**
     * 获取员工调职列表
     */
     public function getPositionList($where = [], $field = 'a.*,b.name,c.branch_name,d.group_name', $order = 'a.id', $paginate = false)
    {
       $this->modelPosition->alias('a');
       $join = [
                    [SYS_DB_PREFIX . 'company b', 'a.company_id = b.id'],
                    [SYS_DB_PREFIX . 'branch c', 'a.branch_id = c.id'],
                    [SYS_DB_PREFIX . 'group d', 'a.group_id = d.id'],
                ];
       $where[ 'a.'.DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        return $this->modelPosition->getList($where, $field, $order, $paginate,$join);
    }

    /**
     * 获取员工列表搜索条件
     */
    public function getWhere($data = [])
    {
        // error_reporting(E_ERROR | E_PARSE );
        $where = [];
        
        !empty($data['staff_name']) && $where['a.staff_name'] = ['like', '%'.$data['staff_name'].'%'];
        !empty($data['phones']) && $where['a.phones'] = ['like', '%'.$data['phones'].'%'];
        !empty($data['card_id']) && $where['a.card_id'] = ['like', '%'.$data['card_id'].'%'];
        !empty($data['entry_time']) && $where['a.entry_time'] = ['eq', $data['entry_time']];
        !empty($data['positive_time']) && $where['a.positive_time'] = ['eq', $data['positive_time']];
        !empty($data['birthday']) && $where['a.birthday'] = ['eq', $data['birthday']];
        !empty($data['group_id']) && $where['a.group_id'] = ['eq', $data['group_id']];
        !empty($data['branch_id']) && $where['a.branch_id'] = ['eq', $data['branch_id']];
        !empty($data['company_id']) && $where['a.company_id'] = ['eq', $data['company_id']];
        !empty($data['audit_status']) && $where['a.audit_status'] = ['eq', $data['audit_status']];
        !empty($data['w_status']) && $where['a.w_status'] = ['eq', $data['w_status']];
        return $where;
    }
    
    //年玲计算

    public function staffBirth($time){
      $year=substr($time,0,4);
      return date('Y')-$year;
    }

      //计算工龄
    public function staffWorkMonth($time){
      $year=substr($time,0,4);
      $month=substr($time,5,2);
      if(date('Y')==$year){
        $w_month=(date('m')-$month).'月';
      }else{
        if($month<date('m')){
          $w_month=(date('Y')-$year).'年'.(date('m')-$month).'月';
        }else{
          if(date('m')==$month){
            $w_month=(date('Y')-$year).'年';
          }else{
            if(date('Y')-$year>1){
              $w_month=(date('Y')-$year-1).'年'.(12+date('m')-$month).'月';
            }else{
              $w_month=(12+date('m')-$month).'月';
            }
          }  
        }
      }
      return $w_month;
    }

    public function staffDataImportS(){

      error_reporting(E_ERROR | E_PARSE );
      vendor('phpoffice/phpexcel/Classes/PHPExcel/Shared/Date');
      $shared = new \PHPExcel_Shared_Date();
      $data = get_excel_data('/www/wwwroot/erp.guxingren.com/public/yghmc.xlsx');
      $title=$data[1];
      unset($data[1]);
      $data=array_values($data);
      dump($title);
      dump($data);die();
    }

     /**
    }
   * 数据导入

   */
    public function staffDataImport($test_url = '',$type='')
    {
      error_reporting(E_ERROR | E_PARSE );
      vendor('phpoffice/phpexcel/Classes/PHPExcel/Shared/Date');
      $shared = new \PHPExcel_Shared_Date();
      $data = get_excel_data('/www/wwwroot/erp.guxingren.com/public'.$test_url);
      $title=$data[1];
      unset($data[1]);
      $data=array_values($data);
    // dump($data);die();
      $url=url('staffRelation');
      switch ($type) {
        case 0://待入职员工导入
          try{
            $importid=0;
            foreach ($data as $key => $value) {
              $data_in['staff_name']=$value[0];
              $data_in['company_id']=$this->logicCompany->getCompanyInfo(['name'=>$value[1]])['id']?$this->logicCompany->getCompanyInfo(['name'=>$value[1]])['id']:1;
              $data_in['branch_id']=$this->logicBranch->getBranchInfo(['branch_name'=>$value[2]])['id']?$this->logicBranch->getBranchInfo(['branch_name'=>$value[2]])['id']:14;
              if(empty($value[3])){
                $data_in['group_id']=6;
              }else{
                $data_in['group_id']=$this->logicGroup->getGroupInfo(['group_name'=>$value[3]])['id']?$this->logicGroup->getGroupInfo(['group_name'=>$value[3]])['id']:6;
              }
              
              $data_in['entry_time']=date('Y-m-d',$shared ->ExcelToPHP($value[4]));
              $data_in['phones']=$value[5];
              $data_in['card_id']=$value[6];
              $data_in['w_status']=1;
              $validate_result = $this->validateStaff->scene('add')->check($data_z); 
              if ($validate_result) {
                $importid++;
                $this->modelStaff->addInfo($data_in);
              }else{
                $msg=['name'=>$value[0],'card_id'=>$value[6],'msg'=>$this->validateStaff->getError()];
                $this->modelImportLog->addInfo($msg);
              }
            }
            action_log('导入', '导入待入职员工，条数：' . count($data));
            return ['code'=>1,'msg'=>'导入'.$importid.'条待入职员工成功'];
          }catch (\Exception $e) {
            return ['code'=>0,'msg'=>$e->getMessage()];
          }
          break;
          case 1://员工基本资料导入
          try{
            // $str="staff_name,name,branch_name,group_name,position,sex,card_id,birthday,phones,email,census_type,car_place,xz_place,pay_name,pay_id,ethnic,marry_status,entry_time,positive_time,education,major,school,graduation,occupational,occupational_type,jj_name,jj_gx,jj_phone,probationpay1,probationpay2,probationpay3,probationpay4,probationpay5,probationpay,positivepay1,positivepay2,positivepay3,positivepay4,positivepay5,positivepay,ht_start,ht_end,ht_time,";
            $importid=0;
            foreach ($data as $key => $value) {
              $data_in['staff_name']=$value[1];
              $data_in['company_id']=$this->logicCompany->getCompanyInfo(['name'=>$value[2]])['id']?$this->logicCompany->getCompanyInfo(['name'=>$value[2]])['id']:1;
              $data_in['branch_id']=$this->logicBranch->getBranchInfo(['branch_name'=>$value[3]])['id']?$this->logicBranch->getBranchInfo(['branch_name'=>$value[3]])['id']:14;
              $data_in['group_id']=$this->logicGroup->getGroupInfo(['group_name'=>$value[4]])['id']?$this->logicGroup->getGroupInfo(['group_name'=>$value[4]])['id']:6;
              $data_in['position']=$value[5];
              $data_in['sex']=$value[6]=='男'?1:2;
              $data_in['card_id']=$value[7];
              $data_in['birthday']=date('Y-m-d',$shared ->ExcelToPHP($value[8]));
              $data_in['phones']=$value[9];
              $data_in['email']=$value[10];
              if($value[11]=='农村户口'){
                $data_in['census_type']=1;
              }else if($value[11]=='城镇户口'){
                $data_in['census_type']=2;
              }else if($value[11]=='外埠农村'){
                $data_in['census_type']=3;
              }else{
                $data_in['census_type']=4;
              }
              $data_in['car_place']=$value[12];
              $data_in['xz_place']=$value[13];
              $data_in['pay_name']=$value[14];
              $data_in['pay_id']=$value[15];
              $data_in['ethnic']=$value[16];
              $data_in['marry_status']=$value[17]=='已婚'?1:2;
              $data_in['entry_time']=date('Y-m-d',$shared ->ExcelToPHP($value[18]));
              $data_in['positive_time']=date('Y-m-d',$shared ->ExcelToPHP($value[19]));
              $data_in['education']=$value[20];
              $data_in['major']=$value[21];
              $data_in['school']=$value[22];
              $data_in['graduation']=date('Y-m-d',$shared ->ExcelToPHP($value[23]));
              $data_in['occupational']=$value[24];
              $data_in['occupational_type']=$value[25];
              $data_in['jj_name']=$value[26];
              $data_in['jj_gx']=$value[27];
              $data_in['jj_phone']=$value[28];
              $data_in['probationpay1']=$value[29];
              $data_in['probationpay2']=$value[30];
              $data_in['probationpay3']=$value[31];
              $data_in['probationpay4']=$value[32];
              $data_in['probationpay5']=$value[33];
              $data_in['probationpay6']=$value[34];
              $data_in['probationpay7']=$value[35];
              $data_in['probationpay']=$value[36];
              $data_in['positivepay1']=$value[37];
              $data_in['positivepay2']=$value[38];
              $data_in['positivepay3']=$value[39];
              $data_in['positivepay4']=$value[40];
              $data_in['positivepay5']=$value[41];
              $data_in['positivepay6']=$value[42];
              $data_in['positivepay7']=$value[43];
              $data_in['positivepay']=$value[44];
              $data_in['ht_start']=date('Y-m-d',$shared ->ExcelToPHP($value[45]));
              $data_in['ht_end']=date('Y-m-d',$shared ->ExcelToPHP($value[46]));
              $data_in['ht_time']=$value[47];
              $data_in['w_status']=2;
              $validate_result = $this->validateStaff->scene('add')->check($data_in); 
              if ($validate_result) {
                 $importid++;
                $this->modelStaff->addInfo($data_in);
              }else{
                $msg=['name'=>$value[1],'card_id'=>$value[10],'phones'=>$value[13],'msg'=>$this->validateStaff->getError()];
                $this->modelImportLog->addInfo($msg);
              }
            }
            action_log('导入', '导入员工基本资料，条数：' . count($data));
            return ['code'=>1,'msg'=>'成功导入'.$importid.'条员工数据'];
          }catch (\Exception $e) {
            return ['code'=>0,'msg'=>$e->getMessage()];
          }
          break;
          case 2://员工培训经历
            try{
              $importid=0;
              foreach ($data as $key => $value) {
                $data_in['t_staff_id']=$this->getStaffInfoId(['card_id'=>$value[1]])['id']?$this->getStaffInfoId(['card_id'=>$value[1]])['id']:0;
                $data_in['t_start_time']=date('Y-m-d',$shared ->ExcelToPHP($value[2]));
                $data_in['t_end_time']=date('Y-m-d',$shared ->ExcelToPHP($value[3]));
                $data_in['t_name']=$value[4];
                $data_in['t_content']=$value[5];
                $data_in['t_certificate']=$value[6];
                $this->modelStaffTrain->addInfo($data_in);
                $importid++;
              }
              action_log('导入', '导入员工培训经历，条数：' . $importid);
              return ['code'=>1,'msg'=>'导入'.$importid.'条员工培训经历'];
            }catch (\Exception $e) {
              return ['code'=>0,'msg'=>$e->getMessage()];
            }
            break;
          case 3://员工工作经历
            try{
              $importid=0;
              foreach ($data as $key => $value) {
                $data_in['w_staff_id']=$this->getStaffInfoId(['card_id'=>$value[1]])['id']?$this->getStaffInfoId(['card_id'=>$value[1]])['id']:0;
                $data_in['w_start_time']=date('Y-m-d',$shared ->ExcelToPHP($value[2]));
                $data_in['w_end_time']=date('Y-m-d',$shared ->ExcelToPHP($value[3]));
                $data_in['w_name']=$value[4];
                $data_in['w_duty']=$value[5];
                $data_in['w_peson']=$value[6];
                $data_in['w_payment']=$value[7];
                $this->modelStaffWork->addInfo($data_in);
                $importid++;
              }
              action_log('导入', '导入员工工作经历，条数：' . $importid);
              return ['code'=>1,'msg'=>'导入'.$importid.'条员工工作经历'];
            }catch (\Exception $e) {
              return ['code'=>0,'msg'=>$e->getMessage()];
            }
            break;
          case 4://员工轨迹记录
            try{
              $importid=0;
              foreach ($data as $key => $value) {
                $data_in['ch_staff_id']=$this->getStaffInfoId(['card_id'=>$value[1]])['id']?$this->getStaffInfoId(['card_id'=>$value[1]])['id']:0;
                $data_in['ch_time']=$value[2];
                $data_in['ch_name']=$value[3];
                $data_in['ch_content']=$value[4];
                $this->modelStaffChild->addInfo($data_in);
                $importid++;
              }
              action_log('导入', '导入员工轨迹，条数：' . $importid);
              return ['code'=>1,'msg'=>'导入'.$importid.'条员工轨迹'];
            }catch (\Exception $e) {
              return ['code'=>0,'msg'=>$e->getMessage()];
            }
            break;
        default:
          break;
      }

    }

  /**
     * 待入职员工添加
     */
    public function staffRelationAdd($data = [])
    {
      $validate_result = $this->validateStaff->scene('add')->check($data); 
      if (!$validate_result) {
        return [RESULT_ERROR, $this->validateStaff->getError()];
      }
      $url = url('staffRelation');
      $data['w_status']=1;
      $result=$this->modelStaff->setInfo($data);//添加基本信息
      $result && action_log('新增', '新增员工，name：' . $data['staff_name']);
        
      return $result ? [RESULT_SUCCESS, '员工添加成功', $url] : [RESULT_ERROR, $this->modelStaff->getError()];

    }

    /**
     * 待入职员工编辑
     */
    public function staffRelationEdit($data = [])
    {
        
        $validate_result = $this->validateStaff->scene('edit')->check($data);
        
        if (!$validate_result) {
            
            return [RESULT_ERROR, $this->validateStaff->getError()];
        }
        $url = url('staffRelation');
        $result = $this->modelStaff->setInfo($data);
        
        $result && action_log('编辑', '编辑待入职员工，：name:' . $data['staff_name']);
        
        return $result ? [RESULT_SUCCESS, '待入职员工编辑成功', $url] : [RESULT_ERROR, $this->modelStaff->getError()];
    }

    /**
     * 员工添加
     */
    public function staffAdd($data = [])
    {
       error_reporting(E_ERROR | E_PARSE ); 
      $data_z=array(
        "company_id" =>$data['company_id'],
        "branch_id" =>$data['branch_id'],
        "group_id" =>$data['group_id'],
        "position" => $data['position'],
        "entry_time" =>$data['entry_time'],
        "positive_time" =>$data['positive_time'],
        "staff_name" =>$data['staff_name'],
        "email" =>$data['email'],
        "sex" => $data['sex'],
        "birthday" =>$data['birthday'],
        "ethnic" =>$data['ethnic'],
        "politics" =>$data['politics'],
        "height_weight" =>$data['height_weight'],
        "marry_status" => $data['marry_status'],
        "worker_time" =>$data['worker_time'],
        "census_type" =>$data['census_type'],
        "card_id" =>$data['card_id'],
        "phones" =>$data['phones'],
        "pay_id" =>$data['pay_id'],
        "pay_name" =>$data['pay_name'],
        "car_place" =>$data['car_place'],
        "xz_place" =>$data['xz_place'],
        "jj_gx" =>$data['jj_gx'],
        "jj_name" =>$data['jj_name'],
        "jj_phone" =>$data['jj_phone'],
        "w_status" =>2,
        // "position_type" =>$data['position_type'],
        // "inter_status" =>$data['inter_status'],
        "inter_name" =>$data['inter_name'],
        "img_id" =>$data['img_id'],
        "education" =>$data['education'],
        "major" =>$data['major'],
        "school" =>$data['school'],
        "graduation" =>$data['graduation'],
        "occupational" =>$data['occupational'],
        "occupational_type" =>$data['occupational_type'],
        "probationpay1" =>$data['probationpay1'],
        "probationpay2" =>$data['probationpay2'],
        "probationpay3" =>$data['probationpay3'],
        "probationpay4" =>$data['probationpay4'],
        "probationpay5" =>$data['probationpay5'],
        "probationpay6" =>$data['probationpay6'],
        "probationpay7" =>$data['probationpay7'],
        'probationpay'=>$data['probationpay1']+$data['probationpay2']+$data['probationpay3']+$data['probationpay4']+$data['probationpay5']+$data['probationpay6']+$data['probationpay7'],
        "positivepay1" =>$data['positivepay1'],
        "positivepay2" =>$data['positivepay2'],
        "positivepay3" =>$data['positivepay3'],
        "positivepay4" =>$data['positivepay4'],
        "positivepay5" =>$data['positivepay5'],
        "positivepay6" =>$data['positivepay6'],
        "positivepay7" =>$data['positivepay7'],
        'positivepay'=>$data['positivepay1']+$data['positivepay2']+$data['positivepay3']+$data['positivepay4']+$data['positivepay5']+$data['positivepay6']+$data['positivepay7'],
        'ht_start'=>$data['ht_start'],
        'ht_end'=>$data['ht_end'],
        'ht_time'=>$data['ht_time'],
      );
      $validate_result = $this->validateStaff->scene('add')->check($data_z); 
      if (!$validate_result) {
        return [RESULT_ERROR, $this->validateStaff->getError()];
      }
      $url = url('staffList');
      $this->modelStaff->startTrans();//开启事务
      try{
        $this->modelStaff->setInfo($data_z);//添加基本信息
        $staff_id=$this->modelStaff->getLastInsID();
        //培训经历
        if($data['t_name']){
          $data_t['t_staff_id']=$staff_id;
          for($i=0;$i<count($data['t_name']);$i++) {
            $data_t['t_name']=$data['t_name'][$i];
            $data_t['t_start_time']=$data['t_start_time'][$i];
            $data_t['t_end_time']=$data['t_end_time'][$i];
            $data_t['t_content']=$data['t_content'][$i];
            $data_t['t_certificate']=$data['t_certificate'][$i];
            $this->modelStaffTrain->addInfo($data_t);
          }
        }
        //工作经历
        if($data['w_name']){
          $data_w['w_staff_id']=$staff_id;
          for($i=0;$i<count($data['w_name']);$i++) {
            $data_w['w_name']=$data['w_name'][$i];
            $data_w['w_start_time']=$data['w_start_time'][$i];
            $data_w['w_end_time']=$data['w_end_time'][$i];
            $data_w['w_duty']=$data['w_duty'][$i];
            $data_w['w_peson']=$data['w_peson'][$i];
            $data_w['w_payment']=$data['w_payment'][$i];
            $this->modelStaffWork->addInfo($data_w);
          }
        }
        //自定义备注
        if($data['ch_name']){
          $data_ch['ch_staff_id']=$staff_id;
          for($i=0;$i<count($data['ch_name']);$i++) {
            $data_ch['ch_time']=$data['ch_time'][$i];
            $data_ch['ch_name']=$data['ch_name'][$i];
            $data_ch['ch_content']=$data['ch_content'][$i];
            $this->modelStaffChild->addInfo($data_ch);
          }
        }
        action_log('新增', '新增员工，name：' . $data['staff_name']);
        $this->modelStaff->commit();//事务提交
        return [RESULT_SUCCESS, '员工添加成功', $url];
      }catch (\Exception $e) {
        return [RESULT_ERROR, $e->getMessage()];
        // 回滚事务
        $this->modelStaff->rollback();
      }
  
    }
    
    /**
     * 获取员工信息
     */
    public function getStaffInfo($where = [])
    {
         $this->modelStaff->alias('a');
        
        $join = [
                    [SYS_DB_PREFIX . 'company b', 'a.company_id = b.id'],
                    [SYS_DB_PREFIX . 'branch c', 'a.branch_id = c.id'],
                    [SYS_DB_PREFIX . 'group d', 'a.group_id = d.id'],
                ];
        return $this->modelStaff->getInfo($where, $field = 'a.*,b.name,c.branch_name,d.group_name', $join, $data = null);
    }

    /**
     * 获取员工id
     */
    public function getStaffInfoId($where = [])
    {
      return $this->modelStaff->getInfo($where, $field = 'id');
    }

    /**
     * 员工编辑
     */
    public function staffEdit($data = [])
    {
      error_reporting(E_ERROR | E_PARSE );
      // dump($data);exit;
       $data_z=array(
        'id'=>$data['id'],
        "company_id" =>$data['company_id'],
        "branch_id" =>$data['branch_id'],
        "group_id" =>$data['group_id'],
        "position" => $data['position'],
        "entry_time" =>$data['entry_time'],
        "positive_time" =>$data['positive_time'],
        "staff_name" =>$data['staff_name'],
        "email" =>$data['email'],
        "sex" => $data['sex'],
        "birthday" =>$data['birthday'],
        "ethnic" =>$data['ethnic'],
        "politics" =>$data['politics'],
        "height_weight" =>$data['height_weight'],
        "marry_status" => $data['marry_status'],
        "worker_time" =>$data['worker_time'],
        "census_type" =>$data['census_type'],
        "card_id" =>$data['card_id'],
        "phones" =>$data['phones'],
        "pay_id" =>$data['pay_id'],
        "pay_name" =>$data['pay_name'],
        "car_place" =>$data['car_place'],
        "xz_place" =>$data['xz_place'],
        "jj_gx" =>$data['jj_gx'],
        "jj_name" =>$data['jj_name'],
        "jj_phone" =>$data['jj_phone'],
        // "position_type" =>$data['position_type'],
        // "inter_status" =>$data['inter_status'],
        "inter_name" =>$data['inter_name'],
        "img_id" =>$data['img_id'],
        "education" =>$data['education'],
        "major" =>$data['major'],
        "school" =>$data['school'],
        "graduation" =>$data['graduation'],
        "occupational" =>$data['occupational'],
        "occupational_type" =>$data['occupational_type'],
        "probationpay1" =>$data['probationpay1'],
        "probationpay2" =>$data['probationpay2'],
        "probationpay3" =>$data['probationpay3'],
        "probationpay4" =>$data['probationpay4'],
        "probationpay5" =>$data['probationpay5'],
        "probationpay6" =>$data['probationpay6'],
        "probationpay7" =>$data['probationpay7'],
        'probationpay'=>$data['probationpay1']+$data['probationpay2']+$data['probationpay3']+$data['probationpay4']+$data['probationpay5']+$data['probationpay6']+$data['probationpay7'],
        "positivepay1" =>$data['positivepay1'],
        "positivepay2" =>$data['positivepay2'],
        "positivepay3" =>$data['positivepay3'],
        "positivepay4" =>$data['positivepay4'],
        "positivepay5" =>$data['positivepay5'],
        "positivepay6" =>$data['positivepay6'],
        "positivepay7" =>$data['positivepay7'],
        'positivepay'=>$data['positivepay1']+$data['positivepay2']+$data['positivepay3']+$data['positivepay4']+$data['positivepay5']+$data['positivepay6']+$data['positivepay7'],
        'ht_start'=>$data['ht_start'],
        'ht_end'=>$data['ht_end'],
        'ht_time'=>$data['ht_time'],
      );
       if($data['w_status']==3){
        $data_z['leave_time']=$data['leave_time'];
        $data_z['leave_yy']=$data['leave_yy'];
       }
        $validate_result = $this->validateStaff->scene('edit')->check($data_z);
        
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateStaff->getError()];
        }
        $url = url('staffList');
        $this->modelStaff->startTrans();//开启事务
      try{
        $this->modelStaff->setInfo($data_z);//修改基本信息
        //培训经历
        // $this->modelStaffTrain->deleteInfo(['t_staff_id' =>$data['id']],true);//删除
        if($data['t_name']){
          $data_t['t_staff_id']=$data['id'];
          for($i=0;$i<count($data['t_name']);$i++) {
            $data_t['t_name']=$data['t_name'][$i];
            $data_t['t_start_time']=$data['t_start_time'][$i];
            $data_t['t_end_time']=$data['t_end_time'][$i];
            $data_t['t_content']=$data['t_content'][$i];
            $data_t['t_certificate']=$data['t_certificate'][$i];
            if($data['t_id'][$i] ==0){
              $this->modelStaffTrain->addInfo($data_t);//新增
            }else{
              $this->modelStaffTrain->save($data_t,['id'=>$data['t_id'][$i]]);//修改
            }
          }
        }
        //工作经历
        if($data['w_name']){
          $data_w['w_staff_id']=$data['id'];
          for($i=0;$i<count($data['w_name']);$i++) {
            $data_w['w_name']=$data['w_name'][$i];
            $data_w['w_start_time']=$data['w_start_time'][$i];
            $data_w['w_end_time']=$data['w_end_time'][$i];
            $data_w['w_duty']=$data['w_duty'][$i];
            $data_w['w_peson']=$data['w_peson'][$i];
            $data_w['w_payment']=$data['w_payment'][$i];
            if($data['w_id'][$i] ==0){
              $this->modelStaffWork->addInfo($data_w);//新增
            }else{
              $this->modelStaffWork->save($data_w,['id'=>$data['w_id'][$i]]);//修改
            }
          }
        }
        if($data['ch_name']){
          $data_ch['ch_staff_id']=$data['id'];
          for($i=0;$i<count($data['ch_name']);$i++) {
            $data_ch['ch_time']=$data['ch_time'][$i];
            $data_ch['ch_name']=$data['ch_name'][$i];
            $data_ch['ch_content']=$data['ch_content'][$i];
            if($data['ch_id'][$i] ==0){
              $this->modelStaffChild->addInfo($data_ch);//新增
            }else{
              $this->modelStaffChild->save($data_ch,['id'=>$data['ch_id'][$i]]);//修改
            }
          }
        }
        action_log('编辑', '员工编辑，name：' . $data['staff_name']);
        $this->modelStaff->commit();//事务提交

        return [RESULT_SUCCESS, '员工编辑成功', $url];
      }catch (\Exception $e) {
        return [RESULT_ERROR, $e->getMessage()];
        // 回滚事务
        $this->modelStaff->rollback();
      }

    }

    /**
     * 员工入职
     */
    public function staffWorkAudit($where = [])
    {
        $where['w_status']=2;
        $url = url('staffRelation');
        $result = $this->modelStaff->setInfo($where);       
        $result && action_log('入职', '员工确认入职，where：' . http_build_query($where));
        return $result ? [RESULT_SUCCESS, '员工确认入职成功', $url] : [RESULT_ERROR,$this->modelStaff->getError(), $url];
    }
    
    /**
     * 员工离职
     */
    public function staffWorkAudits($where = [])
    {
        $where['w_status']=3;
          $url = url('staffList');
          $result = $this->modelStaff->setInfo($where);
                
        $result && action_log('离职', '员工确认离职，where：' .$where['id']);
        return $result ? [RESULT_SUCCESS, '员工确认离职成功', $url] : [RESULT_ERROR,$this->modelStaff->getError(), $url];
    }

    /**
     * 员工审核
     */
    public function staffAudit($where = [])
    {
        $url = url('staffList');
        if($where['audit_status']==1){
          $where['audit_status']=2;
        }else if($where['audit_status']==2){
          $where['audit_status']=1;
        }
        $result = $this->modelStaff->setInfo($where);
                
        $result && action_log('审核', '审核员工，where：' . http_build_query($where));
        $result =$where['audit_status'];
        return $result ? [RESULT_SUCCESS, '员工审核成功', $url] : [RESULT_ERROR,$this->modelStaff->getError(), $url];
    }

    /**
     * 员工删除
     */
    public function staffDel($where = [])
    {
        
        $url = url('staffList');
        
        $result = $this->modelStaff->deleteInfo($where);
                
        $result && action_log('删除', '删除员工，where：' . http_build_query($where));
        
        return $result ? [RESULT_SUCCESS, '员工删除成功', $url] : [RESULT_ERROR, $this->modelStaff->getError(), $url];
    }

    /**
     * 待入职员工删除
     */
    public function staffRelationDel($where = [])
    {
        
        $url = url('staffRelation');
        
        $result = $this->modelStaff->deleteInfo($where);
                
        $result && action_log('删除', '删除待入职员工，where：' . http_build_query($where));
        
        return $result ? [RESULT_SUCCESS, '待入职员工删除成功', $url] : [RESULT_ERROR, $this->modelStaff->getError(), $url];
    }
  
    /**
     * 员工教育经历
     
     */

    public function staffSchool($where = [])
    {
        
      return $this->modelStaffSchool->getList($where);
    }

    /**
     * 员工教育经历删除
     */
    public function staffSchoolDel($where = [])
    {
        
        $url = url('staffList');
        
        $result = $this->modelStaffSchool->deleteInfo($where,true);
                
        $result && action_log('删除', '删除员工教育经历，where：' . http_build_query($where));
        
        return $result ? [RESULT_SUCCESS, '员工删除成功', $url] : [RESULT_ERROR, $this->modelStaff->getError(), $url];
    }

    /**
     * 员工工作经历
     
     */

    public function staffWork($where = [])
    {
        
      return $this->modelStaffWork->getList($where);
    }

    /**
     * 员工工作经历删除
     */
    public function staffWorkDel($where = [])
    {
        
        $url = url('staffList');
        
        $result = $this->modelStaffWork->deleteInfo($where,true);
                
        $result && action_log('删除', '删除员工工作经历，where：' . http_build_query($where));
        
        return $result ? [RESULT_SUCCESS, '员工删除成功', $url] : [RESULT_ERROR, $this->modelStaff->getError(), $url];
    }

    /**
     * 员工直系亲属
     
     */

    public function staffClan($where = [])
    {
        
      return $this->modelStaffClan->getList($where);
    }

    /**
     * 员工直系亲属删除
     */
    public function staffClanDel($where = [])
    {
        
        $url = url('staffList');
        
        $result = $this->modelStaffClan->deleteInfo($where,true);
                
        $result && action_log('删除', '删除员工直系亲属，where：' . http_build_query($where));
        
        return $result ? [RESULT_SUCCESS, '员工删除成功', $url] : [RESULT_ERROR, $this->modelStaff->getError(), $url];
    }

    /**
     * 员工培训经历
     
     */

    public function staffTrain($where = [])
    {
        
      return $this->modelStaffTrain->getList($where);
    }

    /**
     * 员工培训经历删除
     */
    public function staffTrainDel($where = [])
    {
        
        $url = url('staffList');
        
        $result = $this->modelStaffTrain->deleteInfo($where,true);
                
        $result && action_log('删除', '删除员工培训经历，where：' . http_build_query($where));
        
        return $result ? [RESULT_SUCCESS, '员工删除成功', $url] : [RESULT_ERROR, $this->modelStaff->getError(), $url];
    }

    /**
     * 员工备注
     
     */

    public function staffChild($where = [])
    {
        
      return $this->modelStaffChild->getList($where);
    }

    /**
     * 员工备注删除
     */
    public function staffChildDel($where = [])
    {
        
        $url = url('staffList');
        
        $result = $this->modelStaffChild->deleteInfo($where,true);
                
        $result && action_log('删除', '删除员工备注，where：' . http_build_query($where));
        
        return $result ? [RESULT_SUCCESS, '员工删除成功', $url] : [RESULT_ERROR, $this->modelStaff->getError(), $url];
    }

    /**
     * 员工薪资
     
     */

    public function staffPrice($where = [])
    {
        
      return $this->modelStaff->getInfo($where);
    }

    /**
     * 员工薪资编辑
     */
    public function staffPriceEdit($data)
    {
        $url = url('staffPrice',array('id' => $data['id']));
        $result = $this->modelStaff->setInfo($data);
        
        $result && action_log('编辑', '编辑员工薪资，：员工id:' . $data['id']);
        
        return $result ? [RESULT_SUCCESS, '员工薪资成功', $url] : [RESULT_ERROR, $this->modelStaff->getError()];
    }

  /**
     * 员工月薪
     
     */
   public function staffMonthPrice($where = [])
   {
      return $this->modelMonthPrice->getInfo($where);
   }

   /**
     * 员工调薪     
     */
   public function staffAddPrice($where = [])
   {
      return $this->modelPrice->getInfo($where);
   }

   /**
    * 员工调薪列表
    */
    public function staffAddPriceList($where = [], $field = 'a.staff_name,b.*', $order = 'b.create_time desc', $paginate = false) 
    {
       $this->modelStaff->alias('a');
        
        $join = [
                    [SYS_DB_PREFIX . 'price b', 'a.id = b.staff_id'],
                ];
        $where['b.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        return $this->modelStaff->getList($where, $field, $order, $paginate,$join);
    }


    /**
     * 员工调职添加
     */
    public function staffPositionAdd($data)
    {
      $url = url('staffAddPriceList');
      $this->modelStaff->startTrans();//开启事务
      try{
        $this->modelPosition->setInfo($data);
        $data_s=array(
          'company_id'=>$data['company_id'],
          'branch_id'=>$data['branch_id'],
          'group_id'=>$data['group_id'],
          'position'=>$data['p_name'],
        );
        $where['id']= $data['staff_id'];
        $this->modelStaff->updateInfo($where,$data_s);
        action_log('调职', '调职员工，：id:' . $data['staff_id']);
        $this->modelStaff->commit();//事务提交
        return [RESULT_SUCCESS, '员工添加成功', $url];
      }catch (\Exception $e) {
        return [RESULT_ERROR, $e->getMessage()];
        // 回滚事务
        $this->modelStaff->rollback();
      }
    }


    /**
     * 员工调薪添加
     */
    public function staffAddPriceAdd($data)
    {
      $url = url('staffAddPriceList');
      $data['price']=$data['price1']+$data['price2']+$data['price3']+$data['price4']+$data['price5'];
      $result = $this->modelPrice->setInfo($data);
      
      $result && action_log('调薪', '调薪员工，：id:' . $data['staff_id']);
      
      return $result ? [RESULT_SUCCESS, '员工调薪成功', $url] : [RESULT_ERROR, $this->modelPrice->getError()];
    }

    /**
     * 员工调薪编辑
     */
    public function staffAddPriceEdit($data)
    {
        $url = url('staffList');
        $data['price']=$data['price1']+$data['price2']+$data['price3']+$data['price4']+$data['price5'];
        $result = $this->modelPrice->setInfo($data);
        
        $result && action_log('编辑', '编辑员工调薪，：员工id:' . $data['staff_id']);
        
        return $result ? [RESULT_SUCCESS, '员工编辑成功', $url] : [RESULT_ERROR, $this->modelPrice->getError()];
    }

    /**
     * 员工调薪删除
     */
    public function staffAddPriceDel($where = [])
    {
        $url = url('staffPriceList');
        
        $result = $this->modelPrice->deleteInfo($where);
                
        $result && action_log('删除', '删除员工调薪，where：' . http_build_query($where));
        
        return $result ? [RESULT_SUCCESS, '删除调薪成功', $url] : [RESULT_ERROR, $this->modelPrice->getError(), $url];
    }

     /**
    * 员工月薪列表
    */
    public function staffMonthPriceList($where = [], $field = 'a.staff_name,b.*', $order = 'b.create_time desc', $paginate = false) 
    {
       $this->modelStaff->alias('a');
        
        $join = [
                    [SYS_DB_PREFIX . 'month_price b', 'a.id = b.staff_id'],
                ];
        $where['b.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        return $this->modelStaff->getList($where, $field, $order, $paginate,$join);
    }

    /**
     * 员工月薪添加
     */
    public function staffMonthPriceAdd($data)
    {
      $url = url('staffAddPriceList');
      $data['price']=$data['price1']+$data['price2']+$data['price3']+$data['price4'];
      $result = $this->modelMonthPrice->setInfo($data);
      
      $result && action_log('月薪', '月薪员工，：员工id:' . $data['staff_id']);
      
      return $result ? [RESULT_SUCCESS, '员工月薪添加成功', $url] : [RESULT_ERROR, $this->modelStaff->getError()];
    }

    /**
     * 员工月薪编辑
     */
    public function staffMonthPriceEdit($data)
    {
        $url = url('staffList');
        $result = $this->modelMonthPrice->setInfo($data);
        
        $result && action_log('编辑', '编辑员工月薪，：员工id:' . $data['staff_id']);
        
        return $result ? [RESULT_SUCCESS, '员工月薪编辑成功', $url] : [RESULT_ERROR, $this->modelMonthPrice->getError()];
    }

    /**
     * 员工月薪删除
     */
    public function staffMonthPriceDel($where = [])
    {
        $url = url('staffMonthPriceList');
        
        $result = $this->modelMonthPrice->deleteInfo($where);
                
        $result && action_log('删除', '删除员工月薪，where：' . http_build_query($where));
        
        return $result ? [RESULT_SUCCESS, '删除月薪成功', $url] : [RESULT_ERROR, $this->modelMonthPrice->getError(), $url];
    }

    //获取员工人数

    public function staffNum($type,$id)
    {
        if($type=='company'){
            $where=['company_id'=>$id];   
        }else if($type=='branch'){
            $where=['branch_id'=>$id];
        }else if($type=="group"){
           $where=['group_id'=>$id];
        }
        $where[DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        $where['w_status'] = ['eq', 2];
        return $this->modelStaff->getInfo($where, $field='count(id) as num', $join = null, $data = null);
    }


    public function aiImport(){
      $result=curl('http://ad.dscl518.com/index.php/admin/Tables/pxchazhi');
      // dump($result);die;
      $result=json_decode($result,true);
      $titles='名称,资源总数';
      $keys='name,count';

      export_excel($titles, $keys, $result, '资源列表');
      // dump($result);
    }

    /**
     * 导出待入职员工列表
     */
    public function exportStaffRelation($where = [], $field = '', $order = '')
    {
        
        $list = $this->getStaffList($where, $field, $order, false);
        $titles = "员工名,部门组,所属,所属公司,入职时间,手机号,身份证";
        $keys   = "staff_name,group_name,branch_name,name,entry_time,phones,card_id";
        action_log('导出', '导出员工列表');
        foreach ($list as $key => $value) {
            $list[$key]['card_id']="\t".$list[$key]['card_id']."\t";//解决php导出excel 长数字变成科学计数法
        }
        export_excel($titles, $keys, $list, '待入职员工列表');
    }

    /**
     * 导出员工列表
     */
    public function exportStaffBasicList($where = [], $field = '', $order = '')
    {
        error_reporting(E_ERROR | E_PARSE );
        $list = $this->getStaffList($where, $field, $order, false);
        $export_list=$this->modelMember->getInfo(['id'=>MEMBER_ID]);//获取授权的字段
        $member_export=explode(',',$export_list['export']);
        $export_list = $this->logicMember->memberExporetAuthList();//员工基本资料字段
        $titles='序号,';
        $keys ='num,';
        foreach ($export_list as $key => $value) {
            if($member_export[$key]==$value['id']){
              $titles .=$value['value'].',';
              $keys .=$value['name'].',';
            }
        }
        // dump($titles);exit();
        action_log('导出', '导出员工列表');
        $num=0;
        foreach ($list as $key => $value) {
            $num++;
            $list[$key]['num']=$num;
            $list[$key]['card_id']="\t".$list[$key]['card_id']."\t";//解决php导出excel 长数字变成科学计数法
            $list[$key]['pay_id']="\t".$list[$key]['pay_id']."\t";//解决php导出excel 长数字变成科学计数法
            $list[$key]['birth_m']=$this->staffBirth($value['birthday']);
            $list[$key]['work_month']=$this->staffWorkMonth($value['entry_time']);
            // if($value['position_type']==1){
            //   $list[$key]['position_type']='高级';
            // }else if($value['position_type']==2){
            //   $list[$key]['position_type']='初级';
            // }else{
            //   $list[$key]['position_type']='';
            // }
            if($value['sex']==1){
              $list[$key]['sex']='男';
            }else{
              $list[$key]['sex']='女';
            }
            // if($value['inter_status']==1){
            //   $list[$key]['inter_status']='是';
            // }else {
            //   $list[$key]['inter_status']='否';
            // }
            
            if($value['marry_status']==1){
              $list[$key]['marry_status']='已婚';
            }else if($value['marry_status']==2){
              $list[$key]['marry_status']='未婚';
            }else{
              $list[$key]['marry_status']='';
            }
            if($value['census_type']==1){
              $list[$key]['census_type']='农村户口';
            }else if($value['census_type']==2){
              $list[$key]['census_type']='城镇户口';
            }else if($value['census_type']==3){
              $list[$key]['census_type']='外埠农村';
            }else{
              $list[$key]['census_type']='外埠城镇';
            }
        }
        export_excel($titles, $keys, $list, '员工花名册');
    }
    
     /**
   * 导出员工其它信息
   */
      public function exportStaffOther($where,$type)
      {
        $this->modelStaff->alias('a');
        $where['a.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        $titles='姓名,身份证号,';
        $keys='staff_name,card_id,';
        $field='a.staff_name,a.card_id,';
        switch ($type) {
          case 1:
            $join = [
              [SYS_DB_PREFIX . 'staff_train b', 'a.id = b.t_staff_id'],
            ];
            $name='员工培训经历列表';
            $titles .= "开始时间,结束时间,培训机构,培训内容,培训证书";
            $keys   .= "t_start_time,t_end_time,t_name,t_content,t_certificate";
            $field .='b.t_start_time,b.t_end_time,b.t_name,b.t_content,b.t_certificate';
            break;
          case 2:
            $join = [
              [SYS_DB_PREFIX . 'staff_work b', 'a.id = b.w_staff_id'],
            ];
            $name='员工工作经历列表';
            $titles .= "开始时间,结束时间,公司名,职务,证明人,薪酬";
            $keys   .= "w_start_time,w_end_time,w_name,w_duty,w_peson,w_payment";
            $field .='b.w_start_time,b.w_end_time,b.w_name,b.w_duty,b.w_peson,b.w_payment';
            break;
          case 3:
            $join = [
              [SYS_DB_PREFIX . 'staff_child b', 'a.id = b.ch_staff_id'],
            ];
            $name='员工奖惩记录列表';
            $titles .= "奖惩时间,名称,内容";
            $keys   .= "ch_time,ch_name,ch_content";
            $field .='b.ch_time,b.ch_name,b.ch_content';
            break;
          case 4:
            $join = [
              [SYS_DB_PREFIX . 'staff_train b', 'a.id = b.t_staff_id'],
            ];
            $name='员工培训经历列表';
            $titles .= "开始时间,结束时间,培训机构,培训内容,培训证书";
            $keys   .= "t_start_time,t_end_time,t_name,t_content,t_certificate";
            $field .='b.t_start_time,b.t_end_time,b.t_name,b.t_content,b.t_certificate,t_end_time,t_name,t_content,t_certificate';
            break;
          default:
            # code...
            break;
        }
        $list=$this->modelStaff->getList($where,$field,'a.id desc',0,$join);
        foreach ($list as $key => $value) {
          $list[$key]['card_id']="\t".$list[$key]['card_id']."\t";//解决php导出excel 长数字变成科学计数法
        }
        action_log('导出', '导出'.$name);
        export_excel($titles, $keys, $list, $name);          
      }

      public function staffPicture($where){
        return $this->modelPicture->getInfo($where);
      }

     
}
